package com.panels;

import java.awt.GridLayout;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;

import com.dataModel.Quran;
import com.gui.components.QuranPage;

public class PagesPanel extends JPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1285966421759978728L;
	QuranPage leftPage;
	QuranPage rightPage;
	public JSplitPane jSplitPane;
	private static int currentPage=1;


	public PagesPanel()
	{
		leftPage=new QuranPage();
		rightPage=new QuranPage();
		jSplitPane=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
		jSplitPane.setResizeWeight(0.5);
		initGui();
	}
	
	private void initGui()
	{
		this.setLayout(new GridLayout(1,1));
		jSplitPane.setLeftComponent(new JScrollPane(leftPage));
		jSplitPane.setRightComponent(new JScrollPane(rightPage));
		this.add(jSplitPane);
	}
	
	public void displayPage(int pageNumber)
	{
		int rightPageNumber=(pageNumber%2==0)?pageNumber-1:pageNumber;
		int leftPageNumber=(pageNumber%2==0)?pageNumber:pageNumber+1;
		rightPage.displayPage(rightPageNumber);
		leftPage.displayPage(leftPageNumber);
		setCurrentPage(pageNumber);
		String pageNumberText=""+leftPageNumber+" - "+rightPageNumber+"";
		MainPanel.getMainPanel().getNorthPanel().getPageNumberTextField().setText(pageNumberText);
		String nextSowarNames= getNextSowarNames(leftPageNumber);
		String previousSowarNames= getPreviousSowarNames(rightPageNumber);
		MainPanel.getMainPanel().getSouthPanel().setNextSourahName(nextSowarNames);
		MainPanel.getMainPanel().getSouthPanel().setPreviousSourahName(previousSowarNames);
	}
	public void displayNextPage()
	{
		if(getCurrentPage()<Quran.TAHA_OSMAN_PAGE_NUMBERS-2)
		{
			displayPage(getCurrentPage()+2);
		}
	}
	public void displayPreviousPage()
	{
		if(getCurrentPage()>2)
		{
			displayPage(getCurrentPage()-2);
		}
	}
	
	public static int getCurrentPage() {
		return currentPage;
	}

	public static void setCurrentPage(int currentPage) {
		PagesPanel.currentPage = currentPage;
	}
	
	private String getPreviousSowarNames(int pageNumber)
	{
		String sowarNames="";
		
		int i=Quran.getQuranPages()[pageNumber].getStartAyah().getSourahNumber();
		for( ;i-1>0;i--)
		{
			if(Quran.getSowar()[i-1].getPageNumber()<pageNumber)
			{
				sowarNames+=Quran.getSowar()[i-1].getName();
				return sowarNames;
			}
		}
		return sowarNames;
	}

	private String getNextSowarNames(int pageNumber)
	{
		String sowarNames="";
		
		int i=Quran.getQuranPages()[pageNumber].getStartAyah().getSourahNumber()+1;

		for(;i-1<Quran.getSowar().length;i++)
		{
			if(Quran.getSowar()[i-1].getPageNumber()>pageNumber)
			{
				sowarNames+=Quran.getSowar()[i-1].getName();
				return sowarNames;
			}
		}
		
		return sowarNames;
	}

}
